package com.sniper.web.action.admin;

import com.sniper.data.DataValues;
import com.sniper.model.AdminGroup;
import com.sniper.model.AdminRight;
import com.sniper.model.AdminUserGroup;
import com.sniper.mybatis.service.impl.AdminGroupService;
import com.sniper.mybatis.service.impl.AdminUserGroupService;
import com.sniper.utils.FilesUtil;
import com.sniper.utils.PageUtil;
import com.sniper.utils.ValidateUtil;
import com.sniper.web.searchUtils.BaseSearch;
import com.sniper.web.utils.ControllerUtils;
import com.sniper.web.utils.ParamsToHtml;
import com.sniper.web.utils.TreeZTreeUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("${adminPath}/admin-group")
public class AdminGroupController extends AdminBaseController {

    @Resource
    private AdminGroupService adminGroupService;

    @Resource
    AdminUserGroupService adminUserGroupService;

    public String getTreeRightMap() {

        TreeZTreeUtil treeUtil = new TreeZTreeUtil();
        Map<String, Object> params = new HashMap<>();
        params.put("order", "sort asc");
        List<AdminRight> adminRights = adminRightService.query("select", params);

        treeUtil.setAdminRights(adminRights);
        treeUtil.initAll();
        return treeUtil.getTreeNodesAll();
    }


    @RequiresPermissions("admin:group:view")
    @RequestMapping("/")
    public String index(Map<String, Object> map, BaseSearch search) {

        ParamsToHtml html = new ParamsToHtml();
        html.setSniperUrl("/admin-group/delete");

        Map<String, Object> params = new HashMap<>();
        params.put("order", "ctime desc");
        PageUtil page = adminGroupService.page(request, search.getLimit(), params);
        map.put("page", page);
        map.put("sniperMenu", html);
        return forward("/admin/admin-group/index.ftl");
    }

    /**
     * 更新展示,修改展示
     *
     * @param map
     * @return
     */
    @RequiresPermissions("admin:group:insert")
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public String insert(Map<String, Object> map) {

        map.put("adminGroup", new AdminGroup());
        map.put("yes_no", DataValues.YES_NO_INT);
        map.put("treeRightMap", getTreeRightMap());
        return site.getName() + "/admin/admin-group/save-input.jsp";
    }

    @ResponseBody
    @RequiresPermissions("admin:group:insert")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public ControllerUtils.CallBackResult insert(@Validated AdminGroup adminGroup,
                                                 BindingResult result,
                                                 @RequestParam("fromRight") List<AdminRight> fromRight) {

        return new ControllerUtils().ajaxPostResult(result, callBackResult -> {

            adminGroup.setId(FilesUtil.getUUIDName("", false));
            adminGroup.setAdminRight(fromRight);
            adminGroupService.insert(adminGroup);
            return callBackResult;
        });

    }

    /**
     * 更新展示,修改展示
     *
     * @param id
     * @param map
     * @return
     */
    @RequiresPermissions("admin:group:update")
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String update(
            @RequestParam(value = "id", required = false) String id,
            Map<String, Object> map) {
        AdminGroup adminGroup;
        if (ValidateUtil.isValid(id)) {
            adminGroup = adminGroupService.get(id);
        } else {
            return redirect("/admin-group/insert");
        }

        map.put("yes_no", DataValues.YES_NO_INT);
        map.put("adminGroup", adminGroup);
        map.put("treeRightMap", getTreeRightMap());
        return forward("/admin/admin-group/save-input.jsp");
    }

    @ResponseBody
    @RequiresPermissions("admin:group:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ControllerUtils.CallBackResult update(@Validated AdminGroup adminGroup,
                                                 BindingResult result,
                                                 @RequestParam("fromRight") List<AdminRight> fromRight) {

        return new ControllerUtils().ajaxPostResult(result, callBackResult -> {
            adminGroup.setAdminRight(fromRight);
            adminGroupService.update(adminGroup);
            return callBackResult;
        });

    }

    @RequiresPermissions("admin:group:delete")
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Map<String, Object> delete(@RequestParam("delid") String[] delid,
                                      @RequestParam("menuType") String menuType,
                                      @RequestParam("menuValue") String menuValue) {
        Map<String, Object> ajaxResult = new HashMap<>();
        switch (menuType) {
            case "delete":
                try {
                    for (String id : delid) {
                        List<AdminUserGroup> adminUserGroups = adminUserGroupService.listAUG(id);
                        if (adminUserGroups.size() == 0) {
                            adminGroupService.delete(id);
                            ajaxResult.put("code", 1);
                            ajaxResult.put("msg", "success");
                        } else {
                            ajaxResult.put("code", -1);
                            ajaxResult.put("msg", "旗下用户不为空，不得删除。");
                            break;
                        }
                    }
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", "删除失败");
                }
                break;

            default:
                break;
        }
        return ajaxResult;
    }
}